﻿using System.Windows;
using System.Windows.Media;

namespace PocketBook.Controls
{
    public class ParallelLines : FrameworkElement
    {
        public static readonly DependencyProperty StrokeProperty =
            DependencyProperty.Register("Stroke",
                typeof(Brush), typeof(ParallelLines),
                new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty StrokeThicknessProperty =
            DependencyProperty.Register("StrokeThickness",
                typeof(double), typeof(ParallelLines),
                new FrameworkPropertyMetadata(1d, FrameworkPropertyMetadataOptions.AffectsRender));

        public static readonly DependencyProperty SpacingProperty =
            DependencyProperty.Register("Spacing",
                typeof(double), typeof(ParallelLines),
                new FrameworkPropertyMetadata(32d, FrameworkPropertyMetadataOptions.AffectsRender));

        public Brush Stroke
        {
            get { return (Brush) GetValue(StrokeProperty);  }
            set { SetValue(StrokeProperty, value);  }
        }

        public double StrokeThickness
        {
            get { return (double)GetValue(StrokeThicknessProperty); }
            set { SetValue(StrokeThicknessProperty, value); }
        }

        public double Spacing
        {
            get { return (double)GetValue(SpacingProperty); }
            set { SetValue(SpacingProperty, value); }
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            var offset = Spacing;
            if (offset < 1) return;

            var halfLine = StrokeThickness / 2;
            var totalLines = (int)((ActualHeight + halfLine) / offset);

            var verticalGuidelines = new double[totalLines];

            for (var i = 0; i < totalLines; ++i)
                verticalGuidelines[i] = (i + 1) * offset + halfLine;

            var guidelineSet = new GuidelineSet(new double[0], verticalGuidelines);
            drawingContext.PushGuidelineSet(guidelineSet);

            var pen = new Pen(Stroke, StrokeThickness);
            var bounds = new Rect(0, offset, ActualWidth, 0);

            while (bounds.Y < ActualHeight)
            {
                drawingContext.DrawLine(pen, bounds.TopLeft, bounds.BottomRight);
                bounds.Offset(0, offset);
            }

            drawingContext.Pop();
        }
    }
}
